package com.scau402.system1.service.impl;

import com.github.pagehelper.PageInfo;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.core.domain.entity.SysUser;
import com.scau402.common.core.page.TableDataInfo;
import com.scau402.common.utils.DataUtils;
import com.scau402.common.utils.PageUtils;
import com.scau402.common.utils.SecurityUtils;
import com.scau402.system.constants.SystemConstants;
import com.scau402.system1.domain.vo.WmsAdjustJadeDetailVO;
import com.scau402.system1.domain.dto.WmsCreateAdjustBoundOrderDTO;
import com.scau402.system1.domain.po.WmsAdjustBoundOrderDetailPO;
import com.scau402.system1.domain.po.WmsAdjustBoundOrderPO;
import com.scau402.system1.domain.query.WmsAdjustBoundOrderQuery;
import com.scau402.system1.domain.vo.WmsAdjustBoundOrderDetailVO;
import com.scau402.system1.domain.vo.WmsAdjustBoundOrderVO;
import com.scau402.system1.domain.vo.WmsAdjustEmployeeVO;
import com.scau402.system1.domain.vo.WmsJadeVO;
import com.scau402.system1.mapper.*;
import com.scau402.system1.repository.IWmsAdjustDetailRepository;
import com.scau402.system1.repository.IWmsAdjustOrderRepository;
import com.scau402.system1.repository.IWmsStorageRepository;
import com.scau402.system1.repository.IWmsWarehouseRepository;
import com.scau402.system1.service.IWmsAdjustBoundOrderService;
import com.scau402.system1.service.IWmsAuditOrderService;
import com.scau402.system1.utils.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class IWmsAdjustBoundOrderServiceImpl implements IWmsAdjustBoundOrderService {
    @Autowired
    private WmsJadeMapperV2 jadeMapper;
    @Autowired
    private IWmsAdjustBoundOrderMapper adjustOrderMapper;
    @Autowired
    private IdGenerator idGenerator;
    @Autowired
    private IWmsAdjustOrderRepository adjustOrderRepo;
    @Autowired
    private IWmsAdjustDetailRepository adjustDetailRepo;
    @Autowired
    private IWmsAuditOrderService auditOrderService;


    /**
     * 获取库存调整单列表
     * @return
     * @since 2024/1/29
     */
    @Override
    public TableDataInfo listAdjustBoundOrder(WmsAdjustBoundOrderQuery query) {
        if (query.getStartTime() != null) {
            query.setEndTime(Optional.ofNullable(query.getEndTime()).orElse(LocalDateTime.now()));
        }

        SysUser user = SecurityUtils.getLoginUser().getUser();
        //分页
        PageUtils.startPage();
        List<WmsAdjustBoundOrderVO> orderList = adjustOrderRepo.findOrderListByCreator(user,query);
        //分页信息加入MDC
        PageUtils.fetchSessionPageInfo(new PageInfo<>(orderList));
        if(DataUtils.isEmpty(orderList)){
            return new TableDataInfo();
        }
        return PageUtils.getDataTableFromList(orderList);
    }



    /**
     * 创建库存调整单
     * @param createOrder 创建库存调整单参数DTO
     * @return
     * @since 2024/1/29
     */
    @Override
    public AjaxResult createAdjustBoundOrder(WmsCreateAdjustBoundOrderDTO createOrder) {
        // TODO: 参数校验
        List<WmsAdjustJadeDetailVO> jadeList = createOrder.getJadeList();

        // 填充属性
        // TODO: 调整单号，开发阶段暂时使用时间戳作为单号，后续修改
        WmsAdjustBoundOrderPO adjustBoundOrderPO = new WmsAdjustBoundOrderPO(SecurityUtils.getLoginUser(),idGenerator,jadeList,createOrder);

        Long orderId = adjustBoundOrderPO.getId();

        // 创建调整单详情
        List<WmsAdjustBoundOrderDetailPO> orderDetailList = new ArrayList<>();
        for (WmsAdjustJadeDetailVO jade : jadeList) {
            //创建详情单PO
            WmsAdjustBoundOrderDetailPO detail = new WmsAdjustBoundOrderDetailPO();
            detail.build(idGenerator,orderId,jade);

            // 创建审核单
            Long auditId;
            if ((auditId = auditOrderService.create("2", detail.getId())) == null) {
                return AjaxResult.error("创建审核单失败! 请稍后再试!");
            }
            //绑定审核单
            detail.setAuditId(auditId);

            orderDetailList.add(detail);
        }

        // 加入数据库
        adjustOrderRepo.save(adjustBoundOrderPO,orderDetailList);

        return AjaxResult.success();
    }

    /**
     * 获取调整人员名单
     * @return
     */
    @Override
    public AjaxResult getAdjustEmployee() {
        Long tenantId = SecurityUtils.getLoginUser().getTenantId();
        List<WmsAdjustEmployeeVO> list = adjustOrderRepo.getAdjustEmployee(tenantId);
        return AjaxResult.success(list);
    }

    /**
     * 获取盘点单号列表
     * @return
     */
    @Override
    public AjaxResult getCheckOrderCode() {
        List<String> list;
        Long tenantId = SecurityUtils.getLoginUser().getTenantId();
        list = adjustOrderRepo.getCheckOrderCode(tenantId);
        return AjaxResult.success(list);
    }

    /**
     * 获取库存调整单详情
     * @param adjustOrderId 调整单主单id
     * @return
     * @since 2024/1/29
     */
    @Override
    public AjaxResult getAdjustBoundOrderDetail(Long adjustOrderId) {
        // 校验
        WmsAdjustBoundOrderPO adjustOrder = adjustOrderMapper.selectById(adjustOrderId);
        if (adjustOrder == null) {
            return AjaxResult.error(SystemConstants.ADJUST_ORDER_NOT_EXIST);
        }

        // 获取详情
        List<WmsAdjustBoundOrderDetailVO> detailList = adjustDetailRepo.findListByAdjustOrderId(adjustOrderId);

        return AjaxResult.success(detailList);
    }

    /**
     * 获取翡翠详情——适配搜索功能
     * @param barcode 翡翠条码
     * @return
     * @since 2024/1/29
     */
    @Override
    public AjaxResult getJadeDetail(String barcode) {
        //参数校验
        WmsJadeVO totalJadeDetail = jadeMapper.selectAdjustJadeDetailByBarCode(barcode);
        if(totalJadeDetail==null) return AjaxResult.error(SystemConstants.JADE_NOT_EXIST);
        if(totalJadeDetail.getJadeQuantity()<=totalJadeDetail.getOutboundQuantity()) return AjaxResult.error(SystemConstants.JADE_NUM_EMPTY);

        //结果属性赋值
        WmsAdjustJadeDetailVO jadeDetail = new WmsAdjustJadeDetailVO();
        jadeDetail.build(totalJadeDetail,jadeMapper.selectImageIdByBarcode(barcode));

        return AjaxResult.success(jadeDetail);
    }
}
